/*
 * =====================================================================================
 *
 *       Filename:  timestamp.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2012年08月18日 20时32分50秒
 *       Revision:  none
 *       Compiler:  gcc/g++
 *
 *         Author:  wangtengchao , wangtengchao AT gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */

#include "timestamp.h"
#include<time.h>//for gmtime_r
#include<cstdio>//for snprintf
using namespace inm::net;

Timestamp Timestamp::now()
{
	struct timeval tv;
	gettimeofday(&tv,NULL);
	int64_t seconds = tv.tv_sec;///
	return Timestamp(seconds*MicroSecondsPerOneSecond + tv.tv_usec);	
}

std::string Timestamp::toString()
{//localtime's precision is only seconds .So we should combine struct tm with microseconds
//use gmtime_r  --thread safe
	char temp[32] = {'\0'};
	time_t seconds = static_cast<time_t>(microSeconds_ / MicroSecondsPerOneSecond);
	int microseconds = static_cast<int>(microSeconds_ % MicroSecondsPerOneSecond);
	struct tm t;
	gmtime_r(&seconds,&t);
	snprintf(temp,sizeof(temp),"%4d%02d%02d %02d:%02d:%02d.%06d",
			t.tm_year+1900,t.tm_mon+1,t.tm_mday,t.tm_hour+8,t.tm_min,t.tm_sec,microseconds);
	return temp;
}

